package detect;

import interfaces.Detect;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.gson.Gson;

import entities.CmsTechnology;
import entities.Domain;

public class DetectCmsMagento implements Detect {

	@Override
	public void getInfo(Map<String, Object> obj) {
		Document doc = (Document) obj.get("doc");
		Domain domain = (Domain) obj.get("domain");
		
		CmsTechnology cmsTechnology = (CmsTechnology) new Gson().fromJson(domain.getCmsTechnology(), CmsTechnology.class);
		
		if (cmsTechnology == null) {
			cmsTechnology = new CmsTechnology();
		}
		try {
			Elements styles = doc.select("link");
			Elements scripts = doc.select("script");
			
			String cms_name = "";
			String cms_version = "";
			String template_name = "";
			String template_version = "";
			
			for (Element script : scripts) {
				String src = script.attr("src");
				if (src.toLowerCase().contains("varien") || script.html().toLowerCase().contains("varien") || src.toLowerCase().contains("js/mage")) {
					cms_name = "Magento";
					Pattern p = Pattern.compile("([0-9]+[.]*)+[0-9]*");
					Matcher m = p.matcher(src); // get a matcher object
					while(m.find()) {
						cms_version = src.substring(m.start(), m.end());
						break;
					}
					
					cmsTechnology.setN(cms_name);
					cmsTechnology.setV(cms_version);
				}
			}
			
			if (!cms_name.isEmpty()) {
				for (Element style : styles) {
					String style_href = style.attr("href");
					if (template_name.isEmpty() && style_href.toLowerCase().contains("/css/styles.css")) {
						Pattern p = Pattern.compile("[^/]+(/css/styles.css)");
						Matcher m = p.matcher(style_href); // get a matcher object
						while(m.find()) {
							template_name = style_href.substring(m.start(), m.end()).replace("/css/styles.css", "");
							break;
						}
					}
				}
				
				if (!template_name.isEmpty()) {
					cmsTechnology.setTemplate_n(template_name);
					cmsTechnology.setTemplate_v(template_version);
				}
			}
			
			if (!cms_name.isEmpty()) {
				domain.setCmsTechnology(new Gson().toJson(cmsTechnology));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
